package br.urca.impl;

import java.util.List;

import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.transaction.Transactional;

import br.urca.dao.BiItensReservaDAO;
import br.urca.model.BiItensReserva;

@Transactional
public class JPABiItensReservaDAO implements BiItensReservaDAO {
	
	private EntityManager manager;
	
	public JPABiItensReservaDAO() {
		this(null);
	}
	
	@Inject
	public JPABiItensReservaDAO(EntityManager manager) {
		this.manager = manager;
	}

	@Override
	public List<BiItensReserva> getItens(String codReserva) {
		try {
			return this.manager
					.createQuery(
							"SELECT b FROM BiItensReserva b WHERE b.biItensReservaPK.codReserva = :codReserva ",
							BiItensReserva.class)
					.setParameter("codReserva", codReserva).getResultList();
		} catch (Exception e) {
			return null;
		}
	}

	@Override
	public List<BiItensReserva> getItensPendentes(Character codTipoMaterial,
			int codNumeroMaterial) {
		try {
			return this.manager
					.createQuery(
							"SELECT b FROM BiItensReserva b WHERE b.biMateriais.biMateriaisPK.codTipoMaterial = :codTipoMaterial "
									+ " AND b.biMateriais.biMateriaisPK.codNumeroMaterial = :codNumeroMaterial "
									+ " AND b.liberado = :liberado ",
							BiItensReserva.class)
					.setParameter("codTipoMaterial", codTipoMaterial)
					.setParameter("liberado", new Character('F'))
					.setParameter("codNumeroMaterial", codNumeroMaterial)
					.getResultList();
		} catch (Exception e) {
			return null;
		}
	}

	@Override
	public boolean salvar(BiItensReserva itemReserva) {
		try {
			this.manager.merge(itemReserva);
			return true;
		} catch(Exception e) {
			return false;
		}
	}

	@Override
	public List<BiItensReserva> getItensPendentes(List<String> listRegistros) {
		try {
			return this.manager
					.createQuery(
							"SELECT b FROM BiItensReserva b WHERE b.biCopias.biCopiasPK.codRegistro IN (:list) "
									+ " AND b.liberado = :liberado ",
							BiItensReserva.class)
					.setParameter("list", listRegistros)
					.setParameter("liberado", new Character('F'))
					.getResultList();
		} catch (Exception e) {
			return null;
		}
	}

}
